import React, { useEffect, useRef } from 'react'
import { Modal, Form, Input, message } from 'antd'
import Upload, { uploadFile } from '@components/Upload/Index'
import { confirmAction, awaitWrap } from '@js/tool'
import { submitRequest } from './ajax'

const { Item } = Form
const { TextArea } = Input

async function submitHandle (data, caseDetail, task, hide, refreshFn) {
  let fileid = ''
  try {
    const l = await uploadFile(data.file)
    fileid = l.map(li => li.id).join()
  } catch (e) {
    console.error(e)
  }
  const h = message.loading('提交中', 60)
  const formData = formatData(fileid, data.content, caseDetail.id, task)
  h()
  const [e] = await awaitWrap(submitRequest(formData))
  if (e) {
    return false
  }
  hide()
  refreshFn()
}

function formatData (fileid, content, caseid, task) {
  const o = {
    fileid,
    content
  }
  if (task) {
    o.taskid = task.id
  } else {
    o.type = '庭审笔录'
    o.caseid = caseid
  }
  return o
}

function Main ({ visible, hide, caseDetail, task, refreshFn }) {
  const formRef = useRef(null)
  useEffect(() => {
    const c = formRef.current
    if (!visible && c) {
      c.resetFields()
    }
  }, [visible, formRef])
  return (
    <Modal open={visible} title='提交庭审笔录' onCancel={hide} onOk={() => formRef.current.submit()}>
      <Form
        ref={formRef}
        labelCol={{ flex: '88px' }} onFinish={d => {
          confirmAction('您确定要提交吗？', () => {
            submitHandle(d, caseDetail, task, hide, refreshFn).catch(e => console.error(e))
          })
        }}
      >
        <Item label='庭审笔录' name='file' rules={[{ required: true, message: '庭审笔录不能为空' }]}>
          <Upload accept='.docx' maxLength={1} />
        </Item>
        <Item label='备注' name='content'>
          <TextArea />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
